/**
 * 图表测试视图组件
 */
class ChartsView {
    constructor(route) {
        this.route = route;
        this.title = route.title || '图表测试';
        this.charts = {};
    }
    
    /**
     * 渲染页面内容
     */
    async render() {
        return `
            <div class="layui-fluid content-wrapper">
                <div class="content-header">
                    <h2>图表测试</h2>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md6">
                        <div class="layui-card">
                            <div class="layui-card-header">折线图</div>
                            <div class="layui-card-body">
                                <div id="lineChart" style="height: 300px;"></div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-card">
                            <div class="layui-card-header">柱状图</div>
                            <div class="layui-card-body">
                                <div id="barChart" style="height: 300px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md6">
                        <div class="layui-card">
                            <div class="layui-card-header">饼图</div>
                            <div class="layui-card-body">
                                <div id="pieChart" style="height: 300px;"></div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-card">
                            <div class="layui-card-header">散点图</div>
                            <div class="layui-card-body">
                                <div id="scatterChart" style="height: 300px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md12">
                        <div class="layui-card">
                            <div class="layui-card-header">综合图表</div>
                            <div class="layui-card-body">
                                <div id="mixedChart" style="height: 400px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 初始化组件
     */
    async init() {
        console.log('图表组件初始化');
        
        // 等待DOM完全加载
        await this.waitForDOM();
        
        // 初始化图表
        this.initCharts();
        
        // 添加响应式处理
        this.setupResponsive();
        
        // 使用LayUI渲染
        if (typeof layui !== 'undefined') {
            layui.use(['element', 'layer'], function() {
                var element = layui.element;
                var layer = layui.layer;
                element.render();
            });
        }
    }
    
    /**
     * 等待DOM加载完成
     */
    waitForDOM() {
        return new Promise((resolve) => {
            if (document.getElementById('lineChart')) {
                resolve();
            } else {
                setTimeout(() => resolve(), 100);
            }
        });
    }
    
    /**
     * 初始化所有图表
     */
    initCharts() {
        try {
            // 折线图
            this.initLineChart();
            
            // 柱状图
            this.initBarChart();
            
            // 饼图
            this.initPieChart();
            
            // 散点图
            this.initScatterChart();
            
            // 综合图表
            this.initMixedChart();
            
            console.log('所有图表初始化完成');
        } catch (error) {
            console.error('图表初始化失败:', error);
        }
    }
    
    /**
     * 初始化折线图
     */
    initLineChart() {
        const chartDom = document.getElementById('lineChart');
        if (!chartDom) return;
        
        const myChart = echarts.init(chartDom);
        
        const option = {
            title: {
                text: '访问量趋势',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
            },
            yAxis: {
                type: 'value',
                name: '访问量'
            },
            series: [{
                name: '访问量',
                type: 'line',
                data: [120, 132, 101, 134, 90, 230, 210],
                smooth: true,
                itemStyle: {
                    color: '#009688'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(0, 150, 136, 0.3)' },
                        { offset: 1, color: 'rgba(0, 150, 136, 0.1)' }
                    ])
                }
            }]
        };
        
        myChart.setOption(option);
        this.charts.lineChart = myChart;
    }
    
    /**
     * 初始化柱状图
     */
    initBarChart() {
        const chartDom = document.getElementById('barChart');
        if (!chartDom) return;
        
        const myChart = echarts.init(chartDom);
        
        const option = {
            title: {
                text: '系统资源使用',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            xAxis: {
                type: 'category',
                data: ['CPU', '内存', '磁盘', '网络', '进程']
            },
            yAxis: {
                type: 'value',
                name: '使用率(%)'
            },
            series: [{
                name: '使用率',
                type: 'bar',
                data: [65, 45, 78, 32, 89],
                itemStyle: {
                    color: function(params) {
                        const colors = ['#ff5722', '#ffb800', '#5fb878', '#01aaed', '#ff5722'];
                        return colors[params.dataIndex];
                    }
                }
            }]
        };
        
        myChart.setOption(option);
        this.charts.barChart = myChart;
    }
    
    /**
     * 初始化饼图
     */
    initPieChart() {
        const chartDom = document.getElementById('pieChart');
        if (!chartDom) return;
        
        const myChart = echarts.init(chartDom);
        
        const option = {
            title: {
                text: '流量分布',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [{
                name: '流量来源',
                type: 'pie',
                radius: '50%',
                data: [
                    { value: 335, name: '直接访问' },
                    { value: 310, name: '邮件营销' },
                    { value: 234, name: '联盟广告' },
                    { value: 135, name: '视频广告' },
                    { value: 1548, name: '搜索引擎' }
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
        
        myChart.setOption(option);
        this.charts.pieChart = myChart;
    }
    
    /**
     * 初始化散点图
     */
    initScatterChart() {
        const chartDom = document.getElementById('scatterChart');
        if (!chartDom) return;
        
        const myChart = echarts.init(chartDom);
        
        // 生成散点数据
        const data = [];
        for (let i = 0; i < 100; i++) {
            data.push([
                Math.random() * 100,
                Math.random() * 100
            ]);
        }
        
        const option = {
            title: {
                text: '性能分布',
                left: 'center'
            },
            xAxis: {
                name: '响应时间(ms)'
            },
            yAxis: {
                name: '错误率(%)'
            },
            series: [{
                name: '性能点',
                type: 'scatter',
                data: data,
                symbolSize: function(data) {
                    return Math.sqrt(data[0]) * 2;
                },
                itemStyle: {
                    color: '#009688'
                }
            }]
        };
        
        myChart.setOption(option);
        this.charts.scatterChart = myChart;
    }
    
    /**
     * 初始化综合图表
     */
    initMixedChart() {
        const chartDom = document.getElementById('mixedChart');
        if (!chartDom) return;
        
        const myChart = echarts.init(chartDom);
        
        const option = {
            title: {
                text: '系统监控综合视图',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                }
            },
            legend: {
                data: ['CPU使用率', '内存使用率', '进程数'],
                top: 30
            },
            xAxis: [
                {
                    type: 'category',
                    data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00'],
                    axisPointer: {
                        type: 'shadow'
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '使用率(%)',
                    min: 0,
                    max: 100,
                    interval: 20,
                    axisLabel: {
                        formatter: '{value}%'
                    }
                },
                {
                    type: 'value',
                    name: '进程数',
                    min: 0,
                    max: 200,
                    interval: 50,
                    axisLabel: {
                        formatter: '{value}'
                    }
                }
            ],
            series: [
                {
                    name: 'CPU使用率',
                    type: 'line',
                    data: [20, 32, 46, 78, 65, 45, 30],
                    smooth: true,
                    itemStyle: {
                        color: '#ff5722'
                    }
                },
                {
                    name: '内存使用率',
                    type: 'line',
                    data: [30, 42, 56, 68, 55, 35, 40],
                    smooth: true,
                    itemStyle: {
                        color: '#ffb800'
                    }
                },
                {
                    name: '进程数',
                    type: 'bar',
                    yAxisIndex: 1,
                    data: [120, 132, 101, 134, 90, 230, 210],
                    itemStyle: {
                        color: '#009688'
                    }
                }
            ]
        };
        
        myChart.setOption(option);
        this.charts.mixedChart = myChart;
    }
    
    /**
     * 设置响应式处理
     */
    setupResponsive() {
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            this.resizeCharts();
        });
        
        // 使用防抖优化性能
        let resizeTimer;
        window.addEventListener('resize', () => {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(() => {
                this.resizeCharts();
            }, 300);
        });
    }
    
    /**
     * 调整所有图表大小
     */
    resizeCharts() {
        Object.values(this.charts).forEach(chart => {
            if (chart && chart.resize) {
                chart.resize();
            }
        });
    }
    
    /**
     * 更新图表数据
     * @param {string} chartName - 图表名称
     * @param {object} newData - 新数据
     */
    updateChart(chartName, newData) {
        const chart = this.charts[chartName];
        if (chart && newData) {
            chart.setOption(newData);
        }
    }
    
    /**
     * 清理资源
     */
    destroy() {
        console.log('图表组件销毁');
        
        // 销毁所有图表实例
        Object.values(this.charts).forEach(chart => {
            if (chart && chart.dispose) {
                chart.dispose();
            }
        });
        
        // 清理事件监听
        window.removeEventListener('resize', this.resizeCharts);
        
        this.charts = {};
    }
}

// 注册到全局视图组件
if (!window.ViewComponents) {
    window.ViewComponents = {};
}
window.ViewComponents.charts = ChartsView;